import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

// 配置axios默认设置
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
axios.defaults.timeout = parseInt(import.meta.env.VITE_API_TIMEOUT) || 10000

// 响应拦截器处理token过期
let authStore: any = null

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401 && authStore) {
      // token过期，自动登出
      authStore.logout()
      // 可以选择重定向到登录页
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export interface User {
  id: string
  username: string
  email: string
  create_at: string
  update_at: string
}

export interface LoginRequest {
  username: string
  password: string
}

export interface LoginResponse {
  token: string
  user: User
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'))
  const user = ref<User | null>(
    localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')!) : null
  )
  const loading = ref(false)
  const error = ref<string | null>(null)

  const isAuthenticated = computed(() => !!token.value)

  // 设置认证头
  const setAuthHeader = (authToken: string) => {
    axios.defaults.headers.common['Authorization'] = `Bearer ${authToken}`
  }

  // 清除认证头
  const clearAuthHeader = () => {
    delete axios.defaults.headers.common['Authorization']
  }

  // 登录
  const login = async (credentials: LoginRequest): Promise<boolean> => {
    try {
      loading.value = true
      error.value = null

      const response = await axios.post<LoginResponse>('/api/auth/login', credentials)
      
      token.value = response.data.token
      user.value = response.data.user

      // 保存到localStorage
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('user', JSON.stringify(response.data.user))

      // 设置认证头
      setAuthHeader(response.data.token)
      
      return true
    } catch (err: any) {
      error.value = err.response?.data?.message || '登录失败'
      return false
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = () => {
    token.value = null
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    clearAuthHeader()
  }

  // 获取用户信息
  const fetchProfile = async (): Promise<boolean> => {
    try {
      if (!token.value) return false

      setAuthHeader(token.value)
      const response = await axios.get('/api/auth/profile')
      user.value = response.data.data

      // 保存用户信息到localStorage
      localStorage.setItem('user', JSON.stringify(response.data.data))

      return true
    } catch (err) {
      logout()
      return false
    }
  }

  // 初始化认证状态
  const initAuth = async () => {
    if (token.value) {
      // 设置认证头
      setAuthHeader(token.value)

      // 如果没有用户信息，尝试获取
      if (!user.value) {
        const success = await fetchProfile()
        if (!success) {
          logout()
        }
      }
    }
  }

  // 设置全局引用供拦截器使用
  const store = {
    token,
    user,
    loading,
    error,
    isAuthenticated,
    login,
    logout,
    fetchProfile,
    initAuth
  }

  // 设置全局引用
  authStore = store

  return store
})
